package com.yang.qgg_demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.qgg_demo.entity.User;
import com.yang.qgg_demo.mapper.MenuMapper;
import com.yang.qgg_demo.service.ISysRoleService;
import com.yang.qgg_demo.service.IUserService;
import com.yang.qgg_demo.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;

import com.yang.qgg_demo.service.IMenuService;
import com.yang.qgg_demo.entity.Menu;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yang
 * @since 2024-10-28
 */
@RestController
@Slf4j
@RequestMapping("/menu")
    public class MenuController {
    
    @Resource
    private IMenuService menuService;

    @Resource
    private IUserService userService;

    @Resource
    private MenuMapper menuMapper;


    @PostMapping("/save")
    public Boolean save(@RequestBody Menu menu) {
        return menuService.saveOrUpdate(menu);
    }

    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return menuService.removeById(id);
    }

    @GetMapping
    public List<Menu> findAll() {
        return menuService.list();
    }

    @GetMapping("/{id}")
    public Menu findOne(@PathVariable Integer id) {
        return menuService.getById(id);
    }

    @GetMapping("/page")
    public Page<Menu> findPage(@RequestParam String name,
                               @RequestParam Integer pageNum,
                               @RequestParam Integer pageSize) {

        QueryWrapper< Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
     //   queryWrapper.orderByDesc("id");
        return menuService.page(new Page<>(pageNum, pageSize),queryWrapper);
    }

    @GetMapping("/menulist")
    public List<Menu> findPage  () {

        String currentUser =  TokenUtils.getUser();
        List<Menu> list = new LinkedList<>();
        int id = Integer.parseInt(currentUser);
        if (id > 0){
            User user=userService.getById(id);
            int role = user.getRoleid();
            if (role != 1){//如果不是管理员，返回部分权限
                QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
                queryWrapper.like("level",2);
                list.addAll(menuMapper.selectList(queryWrapper));
            }
            else {
                QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
                queryWrapper.like("level",1);
                list.addAll(menuMapper.selectList(queryWrapper));
            }
        }

        return list;
    }

}

